// featurePackage/pages/orderDetail/orderDetail.js

import {
  createPreOrder,//创建预订单编号
  createPreOrderInfo,// 通过预订单编号查询订单信息
  orderPay,
  createOrder,
  confirmOrderPriceComputed,
} from "../../../service/jb_order_service"
import {
  queryAddressDetail
} from "../../../service/jb_address_service"
import {
  queryOrderAbleCoupons
} from "../../../service/jb_coupon_service.js"
import {
  queryUserInfo,
} from "../../../service/jb_mine_service"
import mathUtil from "../../../tools/mathUtils/mathUtil"
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showCouponPop: false,
    addressInfo: {
      name: "",
      phone: "",
      address: "",
      addressId: null,
    },
    jiesuanType: 'buyNow',// buyNow,立即购买，shoppingCart 购物车来的
    preRequestData: {

    },//预订单请求数据
    ableCouponList: [



      // {
      //   "id": 20,
      //   "couponId": 14,
      //   "cid": 0,
      //   "uid": 6,
      //   isSelect: false,
      //   "name": "新年券3",
      //   "money": "10.00",
      //   "minPrice": "0.00",
      //   "type": "receive",
      //   "status": 0,
      //   "createTime": "2024-01-06 20:35:27",
      //   "updateTime": "2024-01-06 20:35:27",
      //   "useTime": null,
      //   "useType": 1,
      //   "primaryKey": null,
      //   "useStartTimeStr": "2024-01-06",
      //   "useEndTimeStr": "2024-02-29"
      // },
      // {
      //   "id": 20,
      //   "couponId": 14,
      //   "cid": 0,
      //   "uid": 6,
      //   isSelect: false,
      //   "name": "新年券3",
      //   "money": "10.00",
      //   "minPrice": "0.00",
      //   "type": "receive",
      //   "status": 0,
      //   "createTime": "2024-01-06 20:35:27",
      //   "updateTime": "2024-01-06 20:35:27",
      //   "useTime": null,
      //   "useType": 1,
      //   "primaryKey": null,
      //   "useStartTimeStr": "2024-01-06",
      //   "useEndTimeStr": "2024-02-29"
      // },



    ],//可用优惠券列表
    preOrderNo: null,//预订单编号
    selectCouponName: "",//选中的优惠券名字
    remarkNum: 0,//备注字数
    remarkText: "",//下单备注
    integralFee: 0,//积分抵扣金额
    giftFee: 0,//礼金抵扣
    isCouponAble: true,//是否有可用的优惠券
    currentIntegral: 0, //当前用户积分
    isUseIntegral: false,//是否使用积分
    isUseGift: false,//是否使用礼金
    currentGift: 0,//当前礼金
    orderInfoVo: {
      "freightFee": "0",
      "userCouponId": null,
      "couponFee": null,
      "proTotalFee": "0",
      "orderProNum": 1,
      "payFee": "0",
      "addressId": null,
      "realName": "",
      "phone": "",
      "province": "",
      "city": "",
      "district": "",
      "detail": "",
      "userIntegral": 0,
      "userBalance": "0.00",
      "remark": null,
      "orderDetailList": [
        // {
        //   "productId": 7,
        //   "productName": "车载小鹿首饰架摆件鹿角树形耳钉首饰展示架耳环架手链饰品收纳首饰挂件 白色",
        //   "attrValueId": 7,
        //   "image": "https://images.jiabao19.com/images/public/maintain/2021/12/25/37382cca048b4011bdbacd3cbbe0814daw1o5x0tco.jpg",
        //   "sku": "默认",
        //   "price": "0.10",
        //   "payNum": 1,
        //   "weight": "0.50",
        //   "volume": "0.00",
        //   "tempId": 1,
        //   "giveIntegral": 0,
        //   "isReply": null,
        //   "isSub": false,
        //   "vipPrice": "0.10",
        //   "productType": 0
        // }
      ],
      "seckillId": 0,
      "bargainId": 0,
      "bargainUserId": null,
      "combinationId": 0,
      "pinkId": 0,
      "cartIdList": null,
      "isVideo": false
    },
    originData: null,
    addressId: null,

    realOrderNo: '',//真实订单号
    jiesuanInfo: null,//结算信息
    goodType: 'normal',
    userInfo: {},
    noWechatPay: false,//是否需要微信支付.
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.type) {
      this.setData({
        jiesuanType: options.type,
        jiesuanInfo: app.globalData.jiesuanInfo
      })
    }
    if (options.goodType) {
      this.setData({
        goodType: options.goodType
      })
    }
    console.log("JJLog:传过来的是：" + JSON.stringify(this.data.jiesuanInfo));

    if (this.data.jiesuanType == 'buyNow') {
      //立即购买
      let orderDetails = [];
      let obj = {
        attrValueId: this.data.jiesuanInfo.skuObj.id,
        productId: this.data.jiesuanInfo.skuObj.productId,
        productNum: this.data.jiesuanInfo.selectNumber,
      }
      if (this.data.goodType == "seckill") {
        obj.productId = this.data.jiesuanInfo.productInfo.productId
        obj.seckillId = this.data.jiesuanInfo.skuObj.productId
      }
      orderDetails.push(obj);
      let preData = {
        preOrderType: this.data.jiesuanType,
        orderDetails: orderDetails
      }
      this.setData({
        preRequestData: preData,
      })
      console.log("JJLog:这个玩意没治嘛：" + JSON.stringify(this.data.preRequestData))
      this.createPreOrderRequest();
    } else {
      //购物车来的
      let arr = this.data.jiesuanInfo.cartList
      let orderlist = [];
      arr.forEach(i => {
        orderlist.push({ shoppingCartId: i.id })
      })
      let obj = {
        preOrderType: this.data.jiesuanType,
        orderDetails: orderlist
      }
      this.setData({
        preRequestData: obj,
      })
      this.createPreOrderRequest();
    }
    this.queryUserInfo();

  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.selectAddressData) {
      console.log("JJLog:这里O：" + JSON.stringify(app.globalData.selectAddressData));
      let res = app.globalData.selectAddressData;
      let data = {
        addressId: res.id,
        name: res.realName,
        phone: res.phone,
        address: res.province + "-" + res.city + '-' + res.district + ' ' + res.detail
      }
      this.setData({
        addressInfo: data,
        'orderInfoVo.addressId': res.id,
      })
      app.globalData.selectAddressData = null;
    }
  },
  //获取个人信息api
  queryUserInfo() {
    queryUserInfo().then(res => {
      if (res.code == 200) {
        this.setData({
          userInfo: res.data,
          currentGift: res.data.giftMoney || 0,//当前礼金
        })
        // if(res.data.giftMoney == 0 || !res.data.giftMoney){
        //   this.setData({
        //     currentGift:0
        //   })
        // }

        app.globalData.userInfo = res.data
      }
    }).catch(err => {
      console.error("JJLog:queryUserInfo", err);
    })
  },

  createPreOrderRequest() {
    wx.showLoading();

    createPreOrder(this.data.preRequestData).then(res => {
      if (res.code == 200) {
        this.setData({
          preOrderNo: res.data.preOrderNo
        })
        this.queryPreOrderInfo();
        this.queryOrderAbleCoupons();
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '创建预订单失败',
        icon: 'none',
        duration: 3000
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 3000)
      console.error("JJLog:createPreOrder", err)
    })
  },
  //查询预订单信息
  queryPreOrderInfo() {
    createPreOrderInfo(this.data.preOrderNo).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          orderInfoVo: res.data.orderInfoVo,
          originData: res.data,
          currentIntegral: res.data.orderInfoVo.userIntegral
        })
        if (res.data.orderInfoVo.addressId) {
          let aRes = res.data.orderInfoVo
          let data = {
            addressId: aRes.addressId,
            name: aRes.realName,
            phone: aRes.phone,
            address: aRes.province + "-" + aRes.city + '-' + aRes.district + ' ' + aRes.detail
          }
          this.setData({
            addressInfo: data
          })
        }
      }
    }).catch(err => {
      wx.hideLoading();
    })
  },
  //查询可用优惠券:
  queryOrderAbleCoupons() {
    this.setData({
      ableCouponList: [],
    })
    queryOrderAbleCoupons(this.data.preOrderNo).then(res => {
      if (res.code == 200) {
        if (res.data && res.data.length > 0) {
          res.data.forEach(i => {
            i.isSelect = false;
          })
          this.setData({
            ableCouponList: res.data || []
          })
        }

      }
    }).catch(err => {
      console.error("JJLog:queryOrderAbleCoupons", err);
    })
  },

  oncePayAction() {
    wx.showLoading({
      title: '支付中...',
    })
    if (!this.data.orderInfoVo.addressId) {
      wx.showToast({
        title: '请先添加您的收货地址',
        icon: "none"
      })
      return;
    }
    let req = {
      "realName": "",
      "phone": "",
      "addressId": this.data.orderInfoVo.addressId,
      "couponId": this.data.orderInfoVo.userCouponId,
      "payType": "weixin",
      "useIntegral": this.data.isUseIntegral,
      "preOrderNo": this.data.preOrderNo,
      "mark": this.data.remarkText,
      "storeId": 0,//自提点id
      "shippingType": 1,//快递类型
      "payChannel": "routine",
      "useGift": this.data.isUseGift,
    }
    if (this.data.noWechatPay) {
      if (this.data.noWechatPay == 1) {
        req.payType = 'gift'
      } else if (this.data.noWechatPay == 2) {
        req.payType = 'yue'
      }
    }
    createOrder(req).then(res => {
      if (res.code == 200) {
        //订单创建成功:
        this.setData({
          realOrderNo: res.data.orderNo
        })
        // if (this.data.orderInfoVo.payFee == 0) {
        //   wx.showToast({
        //     title: '支付成功',
        //     icon: "success",
        //     duration: 2000
        //   })
        //   setTimeout(() => {
        //     wx.navigateTo({
        //       url: '/featurePackage/pages/commonSuccess/commonSuccess?type=0&orderNo=' + res.data.orderNo,
        //     })
        //   }, 2000)
        // } else {
        this.realPayAction(res.data.orderNo);
        // }

      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "创建订单失败",
        icon: "none"
      })
      console.error("JJLog:createOrder", err);
    })
  },
  realPayAction(orderNo) {
    let payType = 'weixin'
    if (this.data.noWechatPay) {
      if (this.data.noWechatPay == 1) {
        payType = 'gift'
      } else if (this.data.noWechatPay == 2) {
        payType = 'yue'
      }
    }
    let requestData = {
      orderNo: orderNo,
      payChannel: "routine",
      payType: payType,
      scene: 0
    }
    orderPay(requestData).then(res => {
      console.log("JJLog:支付回调:" + JSON.stringify(res));
      if (res.code == 200) {
        if (this.data.orderInfoVo.payFee > 0) {
          console.log("JJLog:这里没来")
          let payData = res.data.jsConfig;
          wx.requestPayment({
            timeStamp: payData.timeStamp,
            nonceStr: payData.nonceStr,
            package: payData.packages,
            signType: 'MD5',
            paySign: payData.paySign,
            success: (res) => {
              wx.hideLoading();
              console.log("JJLog:微信支付成功回调:" + JSON.stringify(res));
              wx.showToast({
                title: '支付成功',
                icon: "success",
                duration: 2000
              })
              setTimeout(() => {
                wx.navigateTo({
                  url: '/featurePackage/pages/commonSuccess/commonSuccess?type=0&orderNo=' + orderNo,
                })
              }, 2000)

            },
            fail: (err) => {
              wx.hideLoading();
              wx.showToast({
                title: '支付失败',
                icon: "none"
              })
              console.log("JJLog:微信支付失败回调:" + JSON.stringify(err));
            }
          });
        } else {
          wx.showToast({
            title: '支付成功',
            icon: "success",
            duration: 2000
          })
          setTimeout(() => {
            wx.navigateTo({
              url: '/featurePackage/pages/commonSuccess/commonSuccess?type=0&orderNo=' + orderNo,
            })
          }, 2000)
        }

      }
    }).catch(err => {
      console.error("JJLog购买商品失败:" + JSON.stringify(err));
      wx.hideLoading();
      wx.showToast({
        title: err || "支付失败",
        icon: "none"
      })
    })
  },


  //弹出选择优惠券弹窗
  showSelectCouponAction() {
    this.setData({
      showCouponPop: true
    })
  },
  clickCenterPopupOverlay() {
    this.setData({
      showCouponPop: false
    })
  },
  selectCouponAction(e) {
    let item = e.detail.item;
    let index = e.detail.index;
    if (item.isSelect) {
      //已经选中:
      item.isSelect = false;
      let change = 'ableCouponList[' + index + ']';
      this.setData({
        [change]: item,
        'orderInfoVo.userCouponId': null,
        // 'orderInfoVo.payFee': mathUtil.add(this.data.orderInfoVo.payFee, item.money)
      })

    } else {
      //当前未选中:
      let arr = this.data.ableCouponList;
      arr.forEach(i => {
        i.isSelect = false;
      })
      let seItem = arr[index];
      seItem.isSelect = true;
      this.setData({
        ableCouponList: arr,
        'orderInfoVo.userCouponId': seItem.id,
        selectCouponName: seItem.name
      })
    }
    this.setData({
      showCouponPop: false,
    })
    this.confirmOrderPriceComputed();
  },
  confirmOrderPriceComputed() {
    let data = {
      "addressId": this.data.addressInfo.addressId || null,
      "useIntegral": this.data.isUseIntegral,
      "couponId": this.data.orderInfoVo.userCouponId,
      "shippingType": 1,
      "preOrderNo": this.data.preOrderNo,
      "useGift": this.data.isUseGift,
    }
    console.log("JJLog:传递参数是：" + JSON.stringify(data));

    confirmOrderPriceComputed(data).then(res => {
      if (res.code == 200 && res.data.proTotalFee) {
        this.setData({
          'orderInfoVo.payFee': res.data.payFee,
          'orderInfoVo.proTotalFee': res.data.proTotalFee,
          'orderInfoVo.couponFee': res.data.couponFee,
          'orderInfoVo.freightFee': res.data.freightFee,
          integralFee: res.data.deductionPrice,
          isUseIntegral: res.data.useIntegral,
          currentIntegral: res.data.surplusIntegral,
          giftFee: res.data.usedGift || 0,
          currentGift: res.data.surplusGift || 0,
        })
        if (res.data.payFee == 0) {
          if ((res.data.surplusGift > 0 || res.data.surplusGift == 0) && this.data.isUseGift) {
            this.setData({
              noWechatPay: '1',//礼品卡支付
            })
          } else if (!this.data.isUseGift && this.data.orderInfoVo.userCouponId) {
            this.setData({
              noWechatPay: '2',//优惠券干没得，就是余额支付
            })
          } else if (!this.data.isUseGift && (this.data.orderInfoVo.userCouponId || this.data.isUseIntegral)) {
            //没用礼金，用了优惠券或者用了积分干没得，都是余额支付
            this.setData({
              noWechatPay: '2',//优惠券干没得，就是余额支付
            })
          }

        } else {
          this.setData({
            noWechatPay: false
          })

        }
      }
    }).catch(err => {
      console.error("JJLog:confirmOrderPriceComputed", err);
    })
  },
  //是否使用积分
  onIntegralChange(e) {
    this.setData({
      isUseIntegral: e.detail
    })
    this.confirmOrderPriceComputed();
  },
  //是否使用礼金
  onGiftChange(e) {
    this.setData({
      isUseGift: e.detail
    })
    this.confirmOrderPriceComputed();
  },
  bindRemarkText(e) {
    this.setData({
      remarkText: e.detail.value
    })
  },
  queryAddressDetail() {
    queryAddressDetail(this.data.addressId).then(res => {
      if (res.code == 200) {
        this.setData({
          addressInfo: res.data
        })
      }
    }).catch(err => {

    })
  },

})